package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.RestBean;
import com.example.entity.dto.VisitStats;
import com.example.service.VisitStatsService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 网站访问统计控制器
 *
 * @auth shanyue
 * @date 2025年08月06日11:03
 */
@RestController
@RequestMapping("/api/stats")
public class StatsController {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Resource
    private VisitStatsService visitStatsService;

    /**
     * 获取今日访问量与总访问量
     *
     * @return 成功响应，包含今日访问today和总访问total
     */
    @GetMapping("/visit")
    public RestBean<Map<String, Object>> getVisitStats() {
        //Redis键
        String todayKey = "visit:" + LocalDate.now();
        String totalKey = "visit:total";

        //读取访问数据
        String todayStr = redisTemplate.opsForValue().get(todayKey);
        String totalStr = redisTemplate.opsForValue().get(totalKey);

        //转换为Long类型
        Long today = todayStr != null ? Long.parseLong(todayStr) : 0L;
        Long total = totalStr != null ? Long.parseLong(totalStr) : 0L;

        //封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("today", today);
        result.put("total", total);
        return RestBean.success(result);
    }

    /**
     * 分页获取历史访问记录
     *
     * @param page 当前页码，默认为1
     * @param size 每页数量，默认为10
     * @return 成功响应，包含分页结果
     */
    @GetMapping("/history")
    public RestBean<IPage<VisitStats>> getVisitStatsPage(@RequestParam(defaultValue = "1") long page,
                                                         @RequestParam(defaultValue = "10") long size) {
        //构造分页请求
        Page<VisitStats> pageRequest = new Page<>(page, size);
        //查询分页数据
        IPage<VisitStats> pageResult = visitStatsService.getVisitStatsPage(pageRequest);
        return RestBean.success(pageResult);
    }
}
